require 'rubygame'
require 'yaml'

module OF7
	module Util
		
		FILE_CACHE = {}
		WORK_DIR = File.dirname(__FILE__)
		MAIN_DIR = File.expand(File.join(WORK_DIR, ".."))
		
		Rubygame::Music.autoload_dirs = [
			File.join(get_audio_directory, "music")
		]
		
		Rubygame::Sound.autoload_dirs = [
			File.join(get_audio_directory, "background"),
			File.join(get_audio_directory, "soundfx")
		]
		
		Rubygame::Surface.autoload_dirs = [
			File.join(get_graphics_directory, "animations"),
			File.join(get_graphics_directory, "backgrounds"),
			File.join(get_graphics_directory, "misc"),
			File.join(get_graphics_directory, "mugs"),
			File.join(get_graphics_directory, "portraits"),
			File.join(get_graphics_directory, "tiles")
		]
		
		def load(filepath)
			truedir = File.join(MAIN_DIR, filepath)
			
			if not FILE_CACHE.include? filepath then
				if File.exists? truedir then
					FILE_CACHE[truedir] = YAML.load_file(truedir)
				else
					FILE_CACHE[truedir] = nil
				end
			end
			
			return FILE_CACHE[truedir]
		end
		
		def dump(e, filepath)
			truedir = File.join(MAIN_DIR, filepath)
			
			if not FILE_CACHE.include? filepath then
				if File.exists? truedir then
					FILE_CACHE[truedir] = e
					File.open(truedir, 'w') {|f| YAML.dump(e, f)}
				else
					FILE_CACHE[truedir] = nil
				end
			end
		end
		
		def load_image(imgpath)
			img = File.join(get_graphics_directory, imgpath)
			return Rubygame::Surface[img]
		end
		
		def load_music(mscpath)
			msc = File.join(get_audio_directory, mscpath)
			return Rubygame::Music[msc]
		end
		
		def load_sound(sndpath)
			snd = File.join(get_audio_directory, sndpath)
			return Rubygame::Sound.[snd]
		end
		
		def get_data_directory
			return File.join(MAIN_DIR, "data")
		end
		
		def get_graphics_directory
			return File.join(MAIN_DIR, "graphics")
		end
		
		def get_audio_directory
			return File.join(MAIN_DIR, "audio")
		end
		
	end
end